package com.cskaoyan.service;

import com.cskaoyan.bean.entity.Category;
import com.cskaoyan.bean.entity.CategoryExample;
import com.cskaoyan.bean.entity.Goods;
import com.cskaoyan.bean.entity.GoodsExample;
import com.cskaoyan.bean.vo.*;
import com.cskaoyan.mapper.CategoryMapper;
import com.cskaoyan.mapper.FootprintMapper;
import com.cskaoyan.mapper.GoodsMapper;
import com.cskaoyan.mapper.UserMapper;
import com.cskaoyan.utils.LimitListSizeUtil;
import com.github.pagehelper.PageHelper;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    CategoryMapper categoryMapper;

    @Autowired
    GoodsMapper goodsMapper;

    @Autowired
    FootprintMapper footprintMapper;

    @Autowired
    UserMapper userMapper;

    static CategoryExample categoryExample = new CategoryExample();

    static CategoryExample.Criteria criteria = categoryExample.createCriteria();


    @Override
//    @Order(1)
    public BasePageData<CategoryInfoVo> query() {
        // 目标对象列表
        List<CategoryInfoVo> categoryInfoVoList = new ArrayList<>();

        // 查询所有的一级类目，pid为0就是一级类目
        criteria.andPidEqualTo(0);
        // 先查询所有的一级类目
        List<Category> categories = categoryMapper.selectByExample(categoryExample);

        for (Category category : categories) {
            // 查询所有的二级商品类目，按updateTime降序排序
            CategoryExample categoryExample = new CategoryExample();
            categoryExample.setOrderByClause("update_time desc");
            // 保证每次criteria都不同
            CategoryExample.Criteria criteria = categoryExample.createCriteria();
            // 连接二级类目
            criteria.andPidEqualTo(category.getId());
            // 根据条件查询指定的二级类目
            List<Category> categoryChildrenList = categoryMapper.selectByExample(categoryExample);
            // 保证每次都是一个新的对象
            // 给categoryInfoVo的category一级类目赋值 也 给二级类目children赋值
            CategoryInfoVo categoryInfoVo = new CategoryInfoVo(category.getId(), category.getName(),
                    category.getKeywords(), category.getDesc(), category.getIconUrl(), category.getPicUrl(),
                    category.getLevel(), categoryChildrenList);

            // 给目标对象的列表添加
            categoryInfoVoList.add(categoryInfoVo);

        }
        return BasePageData.ok(categoryInfoVoList);
    }

    @Override
//    @Order(5)  // 规定在查询到信息之后执行
    public BasePageData<CategoryIdAndNameVo> selectNameAndId() {
        // 获取商品类目的id和name
        // l1请求中的存储id和name的list
        List<CategoryIdAndNameVo> idAndNameVos = new ArrayList<>();

        // 查询所有的一级类目，pid为0就是一级类目
        criteria.andPidEqualTo(0);
        // 先查询所有的一级类目
        List<Category> categories = categoryMapper.selectByExample(categoryExample);

        for (Category category : categories) {
            // 给l1请求的id和name赋值
            idAndNameVos.add(new CategoryIdAndNameVo(category.getId(), category.getName()));
        }

        return BasePageData.ok(idAndNameVos);
    }

    /**
     * 新增类目
     *
     * @param category
     * @return
     */
    @Override
    public Category insert(Category category) {
        // 新增之前，为sortOrder和添加、更新事件赋值
        Date date = new Date();
        category.setAddTime(date);
        category.setUpdateTime(date);
        category.setSortOrder((byte) 1);
        categoryMapper.insertSelective(category);

        return categoryMapper.selectByPrimaryKey(category.getId());
    }

    @Override
    public void update(Category category) {
        // 更新编辑的时间
        category.setUpdateTime(new Date());
        categoryMapper.updateByPrimaryKeySelective(category);
    }

    @Override
    public void delete(Category category) {
        categoryMapper.deleteByPrimaryKey(category.getId());
    }

    /**
     * 查询商品类目，当前类目，当前类目的子类别
     *
     * @return
     */
    @Override
    public CatalogIndexVo queryCatalogIndex() {

        CategoryExample categoryExample = new CategoryExample();
        CategoryExample.Criteria criteria = categoryExample.createCriteria();
        criteria.andPidEqualTo(0);

        // 查询所有类目
        List<Category> categories = categoryMapper.selectByExample(categoryExample);

        // 查询当前类目
        Category category = categories.get(0);

        // 查询当前类目的子类目
        // 父类目的id
        Integer categoryId = category.getId();
        // 通过父类目的id查询其子类目
        CategoryExample categoryExample1 = new CategoryExample();
        CategoryExample.Criteria criteria1 = categoryExample1.createCriteria();
        criteria1.andPidEqualTo(categoryId);
        List<Category> categoriesSon = categoryMapper.selectByExample(categoryExample1);

        // 返回查询结果
        CatalogIndexVo catalogIndexVo = new CatalogIndexVo(categories, category, categoriesSon);
        return catalogIndexVo;
    }

    /**
     * 通过market_category表类目的id,查询商品当前类别，当前类别的子类别
     *
     * @param id
     * @return
     */
    @Override
    public CatalogIndexVo queryCatalogCurrent(Integer id) {

        // 查询所有类目
        CategoryExample categoryExample1 = new CategoryExample();
        CategoryExample.Criteria criteria1 = categoryExample1.createCriteria();
        criteria1.andPidEqualTo(0);
        // 查询所有类目
        List<Category> categories = categoryMapper.selectByExample(categoryExample1);

        //查询商品当前类别
        Category category = categoryMapper.selectByPrimaryKey(id);

        // 设置条件
        CategoryExample categoryExample2 = new CategoryExample();
        CategoryExample.Criteria criteria2 = categoryExample2.createCriteria();
        criteria2.andPidEqualTo(id);
        // 查询当前类别的子类别
        List<Category> categoriesSon = categoryMapper.selectByExample(categoryExample2);

        // 返回数据
        CatalogIndexVo catalogIndexVo = new CatalogIndexVo(categories, category, categoriesSon);
        return catalogIndexVo;
    }

    @Override
    public WxGetCategoryInfoAccordingToGoodsCategoryVo getCategoryInfo(Integer id) {
        CategoryExample categoryExample = new CategoryExample();

        // 当前类目
        Category currentCategory = categoryMapper.selectByPrimaryKey(id);

        // 关联类目
        CategoryExample brotherCategoryExample = new CategoryExample();
        CategoryExample.Criteria brotherCriteria = brotherCategoryExample.createCriteria();
        brotherCriteria.andPidEqualTo(currentCategory.getPid());
        List<Category> brotherCategoryList = categoryMapper.selectByExample(brotherCategoryExample);

        // 父类目
        Category parentCategory = categoryMapper.selectByPrimaryKey(currentCategory.getPid());
        WxGetCategoryInfoAccordingToGoodsCategoryVo categoryVo = new WxGetCategoryInfoAccordingToGoodsCategoryVo(currentCategory, brotherCategoryList, parentCategory);
        return categoryVo;
    }

    @Override
    public List<Goods> getGoodsInfo(Integer categoryId,Integer brandId,String keyword,BaseParam baseParam) {
        // 分页
        PageHelper.startPage(baseParam.getPage(), baseParam.getLimit());
        GoodsExample goodsExample = new GoodsExample();
        GoodsExample.Criteria goodsExampleCriteria = goodsExample.createCriteria();
        // 排序
        if(baseParam.getSort() != null && baseParam.getOrder() != null){
            goodsExample.setOrderByClause(baseParam.getSort() + " " + baseParam.getOrder());
        }
        Subject subject = SecurityUtils.getSubject();
        String username = (String) subject.getSession().getAttribute("username");
        Integer userId = userMapper.selectUserIdByUserName(username);

        List<Goods> goodsList = new ArrayList<>();
        if(categoryId != null && categoryId != 0){
            goodsExampleCriteria.andCategoryIdEqualTo(categoryId);
            goodsList = goodsMapper.selectByExample(goodsExample);
        } else if(brandId != null){
            // 根据品牌查询
            Integer[] secCategoryIds = goodsMapper.getCategoryIdAccordingToBrandId(brandId);
            for (Integer secCategoryId : secCategoryIds) {
                Goods goodsInfo = goodsMapper.getGoodsInfoByBrandIdAndCategoryId(secCategoryId, brandId);
                goodsList.add(goodsInfo);
            }
        } else {
            // 根据关键字查询
            List<Goods> goodsListByKeyword = goodsMapper.selectGoodsByKeyword(keyword);
            for (Goods goods : goodsListByKeyword) {
                // 先查询浏览足迹
                Integer[] footGoodsIds = footprintMapper.selectGoodsIdByUserId(userId);
                for (Integer footGoodsId : footGoodsIds) {
                    if(goods.getId() == footGoodsId){
                        // 足迹中有搜索的相似商品，优先添加到商品列表中
                        goodsList.add(goods);
                    }
                }
                if(goodsList.size() < 10){
                    // 足迹中没有相似商品，将搜索到的商品添加进去
                    goodsList.add(goods);
                }
            }
        }

        return goodsList;
    }

    @Override
    public List<Category> getAllSecondCategory(Integer categoryId,Integer brandId,String keyword,BaseParam baseParam) {
        // 分页
        PageHelper.startPage(baseParam.getPage(),baseParam.getLimit());


        CategoryExample categoryExample = new CategoryExample();
        CategoryExample.Criteria categoryExampleCriteria = categoryExample.createCriteria();
        GoodsExample goodsExample = new GoodsExample();
        GoodsExample.Criteria goodsExampleCriteria = goodsExample.createCriteria();
        // 排序
        if(baseParam.getSort() != null && baseParam.getOrder() != null){
            goodsExample.setOrderByClause(baseParam.getSort() + " " + baseParam.getOrder());
        }
        Category currentCategory = null;
        if(categoryId != null && categoryId != 0){
            // 查询要用到一级类目下的商品
            currentCategory = categoryMapper.selectByPrimaryKey(categoryId);
        } else if(brandId != null){
            Integer[] categoryIds = goodsMapper.getCategoryIdAccordingToBrandId(brandId);
            for (Integer secCategoryId : categoryIds) {
                currentCategory = categoryMapper.selectByPrimaryKey(secCategoryId);
                if(currentCategory != null){
                    break;
                }
            }
        } else {
            List<Goods> goodsList = goodsMapper.selectGoodsByKeyword(keyword);
            for (Goods goods : goodsList) {
                Integer secCategoryId = goodsMapper.getCategoryIdByGoodsId(goods.getId());
                currentCategory = categoryMapper.selectByPrimaryKey(secCategoryId);
                if(currentCategory != null){
                    break;
                }
            }
        }
        Integer parentIdOfCurrentCategory = currentCategory.getPid();
        if (categoryId != null) {
            categoryExampleCriteria.andPidEqualTo(parentIdOfCurrentCategory);
        }
        // 获取子兄弟的类目信息
        List<Category> brotherCategoryList = categoryMapper.selectByExample(categoryExample);
        return brotherCategoryList;
    }

    /**
     * 获取所有的一级类目
     * * @return
     */
    @Override
    public List<Category> getAllLevelOneCategorys() {
        CategoryExample categoryExample = new CategoryExample();
        CategoryExample.Criteria categoryExampleCriteria = categoryExample.createCriteria();
        categoryExampleCriteria.andPidEqualTo(0);
        List<Category> categoryList = categoryMapper.selectByExample(categoryExample);
        return categoryList;
    }
}
